package com.cj.mobile.iabp.mvp.presenter;

import static com.cj.mobile.iabp.BuildConfig.IS_DEBUG_DATA;

import android.os.Bundle;
import android.text.TextUtils;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.cj.mobile.iabp.app.config.CommonRetryWithDelay;
import com.cj.mobile.iabp.app.utils.CommonUtils;
import com.cj.mobile.iabp.app.utils.RxUtils;
import com.cj.mobile.iabp.mvp.contract.AddPatientContract;
import com.cj.mobile.iabp.mvp.model.entity.DeptInfo;
import com.cj.mobile.iabp.mvp.model.entity.DictInfo;
import com.cj.mobile.iabp.mvp.model.entity.PatientInfo;
import com.cj.mobile.iabp.mvp.ui.activity.AddSurgeryInfoActivity;
import com.cj.mobile.iabp.mvp.ui.adapter.PrimaryDiagnosisAdapter;
import com.cj.mobile.iabp.mvp.ui.adapter.SecondaryDiagnosisAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 2025/09/24 15:36
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class AddPatientPresenter extends BasePresenter<AddPatientContract.Model, AddPatientContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;

    // 主要诊断数据源
    @Named("Primary")
    @Inject
    List<DictInfo> mPrimaryDiagnosis;
    @Named("PrimaryAdapter")
    @Inject
    PrimaryDiagnosisAdapter mPrimaryAdapter;

    // 次要诊断数据源
    @Named("Secondary")
    @Inject
    List<DictInfo> mSecondaryDiagnosis;
    @Named("SecondaryAdapter")
    @Inject
    SecondaryDiagnosisAdapter mSecondaryAdapter;

    // 当前模式是否为修改
    private boolean isUpdate;
    // 修改模式下的数据源
    private PatientInfo info;

    @Inject
    public AddPatientPresenter(AddPatientContract.Model model, AddPatientContract.View rootView) {
        super(model, rootView);
    }

    public void initData(Bundle bundle) {
        if (bundle != null) {
            info = bundle.getParcelable("info");
            isUpdate = true;
        }

        // 设置标题
        mRootView.getActivity().setTitle(isUpdate ? "修改患者信息" : "新增患者");
        // 加载默认数据
        if (isUpdate)
            mRootView.loadDefaultData(info);

        getDictList();
    }

    /**
     * 获取诊断
     */
    public void getDictList() {
        if (IS_DEBUG_DATA) {
            List<DictInfo> list = new ArrayList<>();
            list.add(new DictInfo(261, "诊断", 0, "1", "1", "冠心病", "1", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(263, "诊断", 0, "1", "3", "急性心梗", "2", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(265, "诊断", 0, "1", "5", "心脏瓣膜病", "3", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(262, "诊断", 0, "1", "2", "先心病", "4", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));
            list.add(new DictInfo(264, "诊断", 0, "1", "4", "主动脉疾病", "5", null, "2025-03-19 17:03:14", "admin", "2025-03-19 17:03:21", "admin", "1", "0"));

            mPrimaryDiagnosis.addAll(list);
            mSecondaryDiagnosis.addAll(list);

            mPrimaryAdapter.notifyDataSetChanged();
            mSecondaryAdapter.notifyDataSetChanged();
        } else {
            mModel.getDictList()
                    .compose(RxUtils.applySchedulers(mRootView))                                    // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<List<DictInfo>>(mErrorHandler) {

                        @Override
                        public void onNext(List<DictInfo> list) {
                            if (CommonUtils.isNotEmpty(list)) {
                                // 清空原有数据
                                mPrimaryDiagnosis.clear();
                                mSecondaryDiagnosis.clear();

                                // 深拷贝 list 中的数据到 mPrimaryDiagnosis 和 mSecondaryDiagnosis
                                for (DictInfo item : list) {
                                    mPrimaryDiagnosis.add(new DictInfo(item));  // 假设 DictInfo 有拷贝构造函数
                                    mSecondaryDiagnosis.add(new DictInfo(item)); // 假设 DictInfo 有拷贝构造函数
                                }

                                // 如果是修改模式，则重新赋值选中的数据
                                if (isUpdate) {
                                    // 主要诊断
                                    if (!TextUtils.isEmpty(info.getDiagnoseF())) {
                                        // 将item值选中
                                        for (DictInfo item : mPrimaryDiagnosis) {
                                            if (item.getValue().equals(info.getDiagnoseF())) {
                                                item.setCheckBox(true);
                                            }
                                        }
                                    }

                                    // 次要诊断
                                    if (!TextUtils.isEmpty(info.getDiagnoseS())) {
                                        // 数据拆分
                                        String[] split = info.getDiagnoseS().split(",");
                                        for (String item : split) {
                                            for (DictInfo item2 : mSecondaryDiagnosis) {
                                                if (item2.getValue().equals(item)) {
                                                    item2.setCheckBox(true);
                                                }
                                            }
                                        }

                                        getDepartmentList(info.getDeptSec());
                                    }
                                }

                                mPrimaryAdapter.notifyDataSetChanged();
                                mSecondaryAdapter.notifyDataSetChanged();
                            } else {
                                mRootView.notDiagnosis();
                            }
                        }
                    });
        }
    }


    /**
     * 获取科室列表
     */
    public void getDepartmentList(String parentId) {
        if (IS_DEBUG_DATA) {
            List<DeptInfo> mList = new ArrayList<>();
            if (parentId.equals("2")) {
                // 朝阳院区
                mList.add(new DeptInfo(4, 2, "主动脉外科中心二区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(5, 2, "主动脉外科中心四区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(6, 2, "冠心病外科中心二区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(7, 2, "冠心病外科中心四区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(8, 2, "小儿心脏科中心二区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(9, 2, "心真与膜外科中心", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));

            } else if (parentId.equals("3")) {
                // 通州院区
                mList.add(new DeptInfo(14, 3, "心外监护室三区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(15, 3, "心外监护室一区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(16, 3, "微创外科中心一区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(17, 3, "结构性心脏病中心一区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(18, 3, "瓣膜与房颜外科中心", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
                mList.add(new DeptInfo(19, 3, "小儿心脏科中心-区", "1", "2025-03-19 11:11:42", "admin", "2025-03-19 17:34:11", "admin", "5", "0"));
            }

            mRootView.loadDepartment(mList);
        } else {
            mModel.getDeptList(parentId)
                    .compose(RxUtils.applySchedulers(mRootView, true, false))                                    // 使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                    .subscribe(new ErrorHandleSubscriber<List<DeptInfo>>(mErrorHandler) {

                        @Override
                        public void onNext(List<DeptInfo> info) {
                            mRootView.loadDepartment(info);
                        }
                    });

        }
    }


    /**
     * 提交事件
     *
     * @param per       0代表预存，如果直接保存这个传1
     * @param deptSec   院区id
     * @param cnt       安装次数
     * @param code      登记号
     * @param name      患者姓名
     * @param height    身高(cm)
     * @param weight    体重(kg)
     * @param sex       性别
     * @param age       年龄
     * @param diagnoseF 主要诊断
     * @param diagnose  其它诊断
     * @param diagnoseS 次要诊断
     * @param deptId    科室id
     * @param area      病房
     * @param bedNo     床位
     * @param friends   患者联系人
     * @param phone     联系人电话
     */
    public void btnSubmit(String per, String deptSec,
                          String cnt, String code, String name, String height, String weight, String sex, String age,
                          String diagnoseF, String diagnose, String diagnoseS,
                          String deptId, String area, String bedNo,
                          String friends, String phone) {
        if (checkInput(cnt, code, name, phone)) {

            if (IS_DEBUG_DATA) {
                onSucc(per, "96", code, name, deptId, deptSec);
            } else {
                // 基本信息
                if (isUpdate) {
                    // 修改接口
                    mModel.updatePatient(per, info.getId(), deptSec,
                                    cnt, code, name, height, weight, sex, age,
                                    diagnoseF, diagnose, diagnoseS,
                                    deptId, area, bedNo,
                                    friends, phone)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<Integer>(mErrorHandler) {

                                @Override
                                public void onNext(Integer commonResponse) {
                                    onSucc(per, info.getId(), code, name, deptId, deptSec);
                                }
                            });
                } else {
                    // 新增接口
                    mModel.addPatient(per, deptSec,
                                    cnt, code, name, height, weight, sex, age,
                                    diagnoseF, diagnose, diagnoseS,
                                    deptId, area, bedNo,
                                    friends, phone)
                            .subscribeOn(Schedulers.io())
                            .retryWhen(new CommonRetryWithDelay(2, 2))    // 遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                            .doOnSubscribe(disposable -> {
                                mRootView.showLoadingSubmit();
                            })
                            .subscribeOn(AndroidSchedulers.mainThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doFinally(() -> {
                                mRootView.hideLoadingSubmit();
                            }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                            .subscribe(new ErrorHandleSubscriber<PatientInfo>(mErrorHandler) {

                                @Override
                                public void onNext(PatientInfo info) {
                                    onSucc(per, info.getId(), code, name, deptId, deptSec);
                                }
                            });
                }

            }

        }
    }

    /**
     * 接口成功后的处理
     *
     * @param per     0代表预存，1代表提交
     * @param id      患者id
     * @param code    登记号
     * @param name    患者姓名
     * @param deptId  科室id
     * @param deptSec 院区id
     */
    private void onSucc(String per, String id, String code, String name, String deptId, String deptSec) {
        if (per.equals("0")) {
            // 预存成功
            mRootView.showMessage("预存成功！");
        } else {
            // 保存成功
            if (isUpdate) {
                // 修改成功
                mRootView.showMessage("修改成功！");
            } else {
                // 添加成功
                mRootView.showMessage("添加成功！");

                // 跳转到手术录入界面
                Bundle mBundle = new Bundle();
                mBundle.putString("id", id);
                mBundle.putString("code", code);
                mBundle.putString("name", name);
                mBundle.putString("deptId", deptId);
                mBundle.putString("deptSec", deptSec);
                ActivityUtils.startActivity(mBundle, AddSurgeryInfoActivity.class);
            }

            // 关闭当前界面
            mRootView.killMyself();
        }
    }

    public boolean checkInput(String cnt, String code, String name, String phone) {
        if (TextUtils.isEmpty(cnt)) {
            mRootView.showMessage("请输入安装次数！");
            return false;
        }

        if (TextUtils.isEmpty(code)) {
            mRootView.showMessage("请输入登记号！");
            return false;
        }

        if (TextUtils.isEmpty(name)) {
            mRootView.showMessage("请输入患者姓名！");
            return false;
        }

        if (!TextUtils.isEmpty(phone)) {
            if (!RegexUtils.isMobileSimple(phone)) {
                mRootView.showMessage("请输入有效的联系人手机号");
                return false;
            }
        }

        return true;
    }

    /**
     * 获取选中的主要诊断
     */
    public String getPrimaryDiagnosis() {
        for (DictInfo info : mPrimaryAdapter.getInfos()) {
            if (info.isCheckBox()) {
//                return info.getCode();
                return info.getValue();
            }
        }

        return "";
    }

    /**
     * 获取选中的次要诊断
     */
    public String getSecondaryDiagnosis() {
        String result = "";
        for (DictInfo info : mSecondaryAdapter.getInfos()) {
            if (info.isCheckBox()) {
                if (TextUtils.isEmpty(result)) {
//                    result = info.getCode();
                    result = info.getValue();
                } else {
//                    result = result + "," + info.getCode();
                    result = result + "," + info.getValue();
                }
            }
        }

        return result;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;

        if (mPrimaryDiagnosis != null) {
            mPrimaryDiagnosis.clear();
            mPrimaryDiagnosis = null;
        }
        mPrimaryAdapter = null;


        if (mSecondaryDiagnosis != null) {
            mSecondaryDiagnosis.clear();
            mSecondaryDiagnosis = null;
        }
        mPrimaryAdapter = null;
    }
}